package com.blog.config;

import com.blog.utils.JwtTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    public final JwtTokenProvider jwtTokenProvider;
    public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求路径
        String path = request.getRequestURI();

        // 放行公开路径
        if (path.startsWith("/public")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头中获取token
        String token = getTokenFromRequest(request);
        try {
            if(token == null) {
                SecurityContextHolder.clearContext();
                response.setStatus(403);
                response.getWriter().write("{\"code\":403, \"message\": \"还未登录,请登录账号再使用\", \"data\":\"\"}");
                throw new AuthenticationException("Token验证失败");
            }
            else if(!jwtTokenProvider.validateToken(token,1)) {
                SecurityContextHolder.clearContext();
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(401);
                response.getWriter().write("{\"code\":401, \"message\": \"token无效或过期\", \"data\":\"\"}");
                throw new AuthenticationException("Token验证失败");
            }
            else {
                //将用户信息存入SecurityContextHolder中,标记为已认证
                List<GrantedAuthority> authorities = jwtTokenProvider.getAuthoritiesFromToken(token);
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(jwtTokenProvider.getEmailFromToken(token), token, authorities));
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\"code\":401, \"message\": \"请重新登录账号\", \"data\":\"\"}");
            e.printStackTrace();
            log.error("JwtAuthenticationFilter:{}", e.getMessage());
        }
    }
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}